package com.wf.ew.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wf.ew.common.JsonResult;
import com.wf.ew.common.PageParam;
import com.wf.ew.common.PageResult;
import com.wf.ew.common.constant.UserConstant;
import com.wf.ew.common.exception.BusinessException;
import com.wf.ew.common.shiro.EndecryptUtil;
import com.wf.ew.common.utils.StringUtil;
import com.wf.ew.system.biz.UserBiz;
import com.wf.ew.system.dao.UserRoleMapper;
import com.wf.ew.system.model.LoginRecord;
import com.wf.ew.system.model.Role;
import com.wf.ew.system.model.User;
import com.wf.ew.system.dao.UserMapper;
import com.wf.ew.system.model.UserRole;
import com.wf.ew.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户表 服务实现类
 *
 * @author wangfan
 * @since 2019-02-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserBiz userBiz;

    @Override
    public User getByUsername(String username) {
        return baseMapper.selectByUsername(username);
    }

    @Override
    public PageResult<User> listUser(PageParam pageParam) {
        List<User> userList = baseMapper.listFull(pageParam);
        // 查询user的角色
        if (userList != null && userList.size() > 0) {
            List<UserRole> userRoles = userRoleMapper.selectByUserIds(getUserIds(userList));
            for (User one : userList) {
                List<Role> tempURs = new ArrayList<>();
                for (UserRole ur : userRoles) {
                    if (one.getId().equals(ur.getUserId())) {
                        tempURs.add(new Role(ur.getRoleId(), ur.getRoleName(), null));
                    }
                }
                one.setRoles(tempURs);
                one.setRoles(tempURs);
            }
        }
        return new PageResult<>(userList, pageParam.getTotal());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addUser(User user, List<Integer> roleIds, User loginUser) {
        if (baseMapper.selectByUsername(user.getName()) != null) {
            throw new BusinessException("账号" + user.getName() + "已经存在");
        }
        if(loginUser == null) {
            loginUser = new User();
            loginUser.setId("1");
            user.setState("正常");
            user.setCompanyId("4");
            user.setPassword(EndecryptUtil.encrytMd5(user.getPassword(), 3));
        }
        //没有客户id为卡奥斯的操作2 有客户id的情况是公司的客户3
        if(user.getCustomerId().equals("") || user.getCustomerId() == null) {
            user.setRoleState("2");
        } else {
            user.setRoleState("3");
        }
        KeyHolder key= userBiz.add(user, loginUser);
        int keyid = key.getKey().intValue();
        if (keyid>0) {
            if (userRoleMapper.insertBatch(keyid+"", roleIds) < roleIds.size()) {
                throw new BusinessException("添加失败");
            }
        }
        return keyid>0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUser(User user, List<Integer> roleIds) {
        user.setName(null);  // 账号不能修改
        boolean result = baseMapper.updateById(user) > 0;
        if (result) {
            userRoleMapper.delete(new UpdateWrapper<UserRole>().eq("id", user.getId()));
            if (userRoleMapper.insertBatch(user.getId(), roleIds) < roleIds.size()) {
                throw new BusinessException("修改失败");
            }
        }
        return result;
    }

    /**
     * 获取用户id
     */
    private List<String> getUserIds(List<User> userList) {
        List<String> userIds = new ArrayList<>();
        for (User one : userList) {
            userIds.add(one.getId());
        }
        return userIds;
    }

    @Override
    public JsonResult addLoginRecord(LoginRecord loginRecord){
        if (userBiz.addLoginRecord(loginRecord)) {
            return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }


    @Override
    public String list(PageResult<T> page, User user, User loginUser) {
        return userBiz.list(page,user,loginUser);
    }

    @Override
    public List<User> list(User user, User loginUser) {
        return userBiz.list(user,loginUser);
    }
    @Override
    public List<UserRole> listUserRole(User user) {
        return userBiz.listUserRole(user);
    }
    @Override
    public JsonResult userNameUnique(User user) {
        boolean ret = true;
        List<User> list = userBiz.userNameUnique(user);
        if(user.getId()!=null&& !user.getId().equals("")){
            User u1 = userBiz.getById(user);
            if(!u1.getName().equals(user.getName())){
                if(list!=null && list.size()>0){
                    ret = false;
                }
            }
        } else {
            if(list!=null && list.size()>0){
                ret = false;
            }
        }
        if(ret){
            return JsonResult.ok("可以使用帐号!");
        }
        return JsonResult.error("该帐号已使用,请重新填写!");

    }

    @Override
    public User getById(User user) {
        return userBiz.getById(user);
    }

    @Override
    public User getByOpenId(User user) {
        return userBiz.getByOpenId(user);
    }

    @Transactional
    @Override
    public JsonResult add(User user, List<Integer> roleIds, User loginUser) {
        if (baseMapper.selectByUsername(user.getName()) != null) {
            throw new BusinessException("账号已经存在");
        }
        //没有客户id为卡奥斯的操作2 有客户id的情况是公司的客户3
        if(user.getCustomerId().equals("") || user.getCustomerId() == null) {
            user.setRoleState("2");
        } else {
            user.setRoleState("3");
        }
        KeyHolder key= userBiz.add(user, loginUser);
        int keyid = key.getKey().intValue();
        if (userRoleMapper.insertBatch(keyid+"", roleIds) < roleIds.size()) {
            throw new BusinessException("添加失败");
        }
        return JsonResult.ok("添加成功");
    }

    @Transactional
    @Override
    public JsonResult update(User user, User loginUser) {
        if (userBiz.update(user, loginUser)) {
            userBiz.deleteUserRole(user);
            String[] roleIds2 = user.getRoleIds().split(",");
            List<Integer> roleIds = new ArrayList<Integer>();
            for (String s : roleIds2) {
                Integer s2 = Integer.valueOf(s);
                roleIds.add(s2);
            }
            if (userRoleMapper.insertBatch(user.getId(), roleIds) < roleIds.size()) {
                throw new BusinessException("修改失败");
            }
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @Transactional
    @Override
    public JsonResult delete(User user, User loginUser) {
        if (userBiz.delete(user, loginUser)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }


    @Override
    public JsonResult udpatePsw(User user, User loginUser, boolean deft) {
        if(deft){
            user.setPassword(EndecryptUtil.encrytMd5(UserConstant.DEFAULT_PSW, 3));
        } else {
            if (StringUtil.isBlank(user.getOldPsw(), user.getPassword())) {
                return JsonResult.error("参数不能为空");
            }
            if (loginUser == null) {
                return JsonResult.error("未登录");
            }
            if (!loginUser.getPassword().equals(EndecryptUtil.encrytMd5(user.getOldPsw(), 3))) {
                return JsonResult.error("原密码输入不正确");
            }
            user.setId(loginUser.getId());
            user.setPassword(EndecryptUtil.encrytMd5(user.getPassword(), 3));
        }
        if (userBiz.udpatePsw(user, loginUser)) {
            if(deft){
                return JsonResult.ok("修改成功，初始密码为" + UserConstant.DEFAULT_PSW);
            } else {
                return JsonResult.ok("修改成功!");
            }

        }
        return JsonResult.error("修改失败");
    }

    @Override
    public JsonResult udpateState(User user, User loginUser) {
        if (userBiz.udpateState(user, loginUser)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @Override
    public String loginRecordList(PageResult<T> page, LoginRecord loginRecord) {
        return userBiz.loginRecordList(page,loginRecord);
    }

}
